<template>
	<el-drawer
		v-model="drawerVisible"
		@closed="cancelForm(ruleFormRef)"
		:destroy-on-close="true"
		:close-on-click-modal="false"
		size="50%"
		:title="`${drawerProps.title}客户`"
	>
		<el-form
			ref="ruleFormRef"
			:model="fromVerification"
			:rules="rules"
			label-width="150px"
			label-position="left"
			class="demo-ruleForm"
			status-icon
		>
			<el-form-item label="企业名称：" prop="companyName">
				<el-input
					:disabled="drawerProps.row ? true : false"
					v-model="fromVerification.companyName"
					type="text"
					placeholder="输入内容"
				/>
			</el-form-item>
			<el-form-item label="企业简称：" prop="companyAlias">
				<el-input v-model="fromVerification.companyAlias" type="text" placeholder="输入内容" />
			</el-form-item>
			<el-form-item label="客户类型：" prop="companyTypeId">
				<el-select v-model="fromVerification.companyTypeId" style="width: 350px" placeholder="选择客户类型">
					<el-option
						v-for="item in companyType"
						:key="item.companyTypeId"
						:label="item.companyTypeName"
						:value="item.companyTypeId"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="企业LOGO:" prop="companyLogo">
				<upload v-model:image-url="fromVerification.companyLogo">
					<template #tip>
						<div class="el-upload__tip">支持格式：.jpg .png,文件大小不能超过500kb</div>
					</template>
				</upload>
			</el-form-item>
			<el-form-item label="客户地址：" prop="companyAddress">
				<el-input v-model="fromVerification.companyAddress" placeholder="输入内容" />
			</el-form-item>
			<el-form-item label="联系人姓名：" prop="contactsUserName">
				<el-input v-model="fromVerification.contactsUserName" placeholder="输入内容" />
			</el-form-item>
			<el-form-item label="联系人电话：" prop="contactsUserTel">
				<el-input v-model.trim="fromVerification.contactsUserTel" placeholder="输入内容" />
			</el-form-item>
			<el-form-item prop="contactsUserIdNo" label="身份证号码：">
				<el-input v-model="fromVerification.contactsUserIdNo" placeholder="输入内容" />
			</el-form-item>

			<el-form-item label="身份证照片：">
				<upload width="400px" height="200px" v-model:image-url="fromVerification.contactsUserIdNoPhoto">
					<template #tip>
						<div class="el-upload__tip">支持格式:jpg、png ,单个文件不能超过20MB</div>
					</template>
				</upload>
			</el-form-item>
			<el-form-item label="组织机构代码：">
				<el-input v-model="fromVerification.organizationCode" placeholder="输入内容" />
			</el-form-item>

			<el-form-item label="营业执照照片：">
				<upload width="400px" height="200px" v-model:image-url="fromVerification.businessLicensePhoto">
					<template #tip>
						<div class="el-upload__tip">支持格式:jpg、png ,单个文件不能超过20MB</div>
					</template>
				</upload>
			</el-form-item>
			<el-form-item label="使用期限：" prop="usageTime">
				<el-input disabled v-model.number="fromVerification.usageTime" placeholder="请选择日期">
					<template #append> 天 </template>
				</el-input>
			</el-form-item>

			<el-form-item label="有效日期开始时间：" prop="authorizeBeginTime" style="width: auto">
				<el-date-picker
					v-model="fromVerification.authorizeBeginTime"
					value-format="YYYY-MM-DD"
					type="date"
					placeholder="请选择开始时间"
				/>
			</el-form-item>
			<el-form-item label="有效日期结束时间：" prop="authorizeEndTIme" style="width: auto">
				<el-date-picker
					v-model="fromVerification.authorizeEndTIme"
					value-format="YYYY-MM-DD"
					type="date"
					placeholder="请选择结束时间"
				/>
			</el-form-item>
			<div style="margin-bottom: 15px; margin-left: 150px">
				<span class="el-upload__tip"
					>使用期限从有效日期开始开始时间开始计算，截止日一过则自动关闭客户所有账号，不可再登录使用</span
				>
			</div>
			<el-form-item label="客户端授权码数量：" prop="clientAuthorizationCodeNumber">
				<el-input v-model.number="fromVerification.clientAuthorizationCodeNumber" placeholder="输入内容">
					<template #append> 台 </template>
				</el-input>
			</el-form-item>

			<el-form-item label="登录账号：" prop="contactsUserLoginName">
				<el-input v-model="fromVerification.contactsUserLoginName" placeholder="输入内容" />
			</el-form-item>
			<el-form-item label="状态：" prop="states">
				<el-radio-group v-model="fromVerification.states">
					<el-radio :label="true">启用</el-radio>
					<el-radio :label="false">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item></el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="cancelForm(ruleFormRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit">保存</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref, reactive, watch, nextTick } from "vue";
import upload from "@/components/Upload/Img.vue";
import userInfoApi from "@/api/modules/userInfo";
import companyInfoApi from "@/api/modules/companyInfo";
import { GlobalStore } from "@/stores";
import md5 from "js-md5";
const globalStore = GlobalStore();
interface DrawerProps {
	title: string;
	isView: boolean;
	row: any;
	api?: (params: any) => Promise<any>;
	getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: "",
	row: null
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
	drawerProps.value = params;
	drawerVisible.value = true;
};
// 表单验证数据
let fromVerification = ref({
	id: "",
	companyName: "",
	companyAlias: "",
	companyTypeId: "",
	companyLogo: "",
	companyAddress: "",
	organizationCode: "",
	businessLicensePhoto: "",
	usageTime: "",
	authorizeBeginTime: "",
	authorizeEndTIme: "",
	clientAuthorizationCodeNumber: null,
	contactsUserId: "",
	contactsUserName: "",
	contactsUserTel: "",
	contactsUserIdNo: "",
	contactsUserIdNoPhoto: "",
	contactsUserLoginName: "",
	platformId: "",
	states: true
});
//账号信息信息
const userrequest = reactive({
	userName: "",
	userTel: "",
	userIdNo: "",
	userIdNoPhoto: "",
	loginName: "",
	passWord: md5("a123456").toUpperCase(),
	platformId: "",
	states: true
});
interface TypeItem {
	companyTypeId: string;
	companyTypeName: string;
}
const companyType = ref<TypeItem[]>([]);
// 获取客户类型数据
const getCompanyTypeList = async () => {
	let { result } = await companyInfoApi.GetCompanyTypeInfoList();
	if (result.code != 200) return;
	companyType.value = result.data.map((i: any) => {
		return {
			companyTypeId: i.id,
			companyTypeName: i.companyTypeName
		};
	});
};
getCompanyTypeList();
//初始化编辑的时候需要注入相关数据
const init = () => {
	nextTick(async () => {
		if (!drawerProps.value.row) return;
		console.log(drawerProps.value.row.surplusAuthorization);
		let { result } = await companyInfoApi.GetCompanyInfo({ id: drawerProps.value.row.id });
		fromVerification.value = { ...result.data };
	});
};
watch(
	() => drawerVisible.value,
	val => {
		if (!val) return;
		init();
	}
);
// 监听计算日期天数
watch(
	() => fromVerification.value.authorizeEndTIme,
	() => {
		if (!fromVerification.value.authorizeBeginTime && !fromVerification.value.authorizeEndTIme) return;
		let time =
			new Date(fromVerification.value.authorizeEndTIme).getTime() - new Date(fromVerification.value.authorizeBeginTime).getTime();
		fromVerification.value.usageTime = (Math.floor(Math.abs(time) / 86400000) + "") as string;
	}
);
watch(
	() => fromVerification.value.authorizeBeginTime,
	() => {
		if (!fromVerification.value.authorizeBeginTime && !fromVerification.value.authorizeEndTIme) return;
		let time =
			new Date(fromVerification.value.authorizeEndTIme).getTime() - new Date(fromVerification.value.authorizeBeginTime).getTime();
		fromVerification.value.usageTime = (Math.floor(Math.abs(time) / 86400000) + "") as string;
	}
);
const checkAccount = (rule: any, value: any, callback: any) => {
	if (value === "") callback("请输入登录账号");
	if (drawerProps.value.row.id) callback();
	userInfoApi.GetLoginUserInfo({ loginName: value, passWord: "" }).then(res => {
		if (res.result.code != 200) {
			callback("登录账号已存在！");
			return;
		}
		callback();
	});
};
const checkPhoneNo = (rule: any, value: any, callback: any) => {
	const regexp = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/;
	if (value === "") callback("请输入手机号码");
	if (!regexp.test(value)) {
		callback(new Error("请输入正确的手机号码"));
	} else {
		if (drawerProps.value.row.id) callback();
		userInfoApi.VerificationUserTel({ userTel: value }).then(res => {
			if (res.result.code != 200) {
				callback("手机号码已存在！");
				return;
			}
			callback();
		});
	}
};
const checkAuthorizationCodeNumber = (rule: any, value: any, callback: any) => {
	if (!drawerProps.value.row) {
		if (value === "") {
			callback("请输入客户端授权码数量");
		} else {
			callback();
		}
	} else {
		let { clientAuthorizationCodeNumber, surplusAuthorization } = drawerProps.value.row;
		let num: number = clientAuthorizationCodeNumber - surplusAuthorization;
		if (value === "") {
			callback("请输入客户端授权码数量");
		} else {
			if (num < 1) {
				callback();
			} else {
				if (value < num) {
					callback(`输入的值要大于现已经授权的数量${num}台`);
				} else {
					callback();
				}
			}
		}
	}
};
const rules = reactive<FormRules>({
	companyName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
	companyAlias: [{ required: true, message: "请输入企业简称", trigger: "blur" }],
	companyTypeId: [{ required: true, message: "请选择客户类型", trigger: "change" }],
	companyLogo: [{ required: true, message: "请上传企业LOGO", trigger: "change" }],
	companyAddress: [{ required: true, message: "请输入客户地址", trigger: "blur" }],
	contactsUserName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
	contactsUserTel: [
		{ required: true, message: "请输入联系人电话", trigger: "blur" },
		{ min: 11, max: 11, message: "联系人电话11位", trigger: "blur" },
		{ validator: checkPhoneNo, trigger: "blur" }
	],
	usageTime: [{ required: true, message: "请输入使用期限", trigger: "blur" }],
	authorizeBeginTime: [{ required: true, message: "请选择有效日期", trigger: "change" }],
	authorizeEndTIme: [{ required: true, message: "请选择有效日期", trigger: "change" }],
	clientAuthorizationCodeNumber: [
		{ required: true, message: "请输入客户端授权码数量", trigger: "blur" },
		{ validator: checkAuthorizationCodeNumber, trigger: "blur" }
	],
	contactsUserLoginName: [
		{ required: true, message: "请输入登录账号", trigger: "blur" },
		{ min: 3, max: 16, message: "请输入3-16英文数字的登录账号", trigger: "blur" },
		{ validator: checkAccount, trigger: "blur" }
	],
	states: [{ required: true, message: "请选择客户状态", trigger: "change" }],
	contactsUserIdNo: [
		{ required: false, message: "请输入身份证号码", trigger: "blur" },
		{ pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/, message: "请输入正确的身份证号码", trigger: "blur" }
	]
});
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
// 取消
const cancelForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	fromVerification.value = {
		id: "",
		companyName: "",
		companyAlias: "",
		companyTypeId: "",
		companyLogo: "",
		companyAddress: "",
		organizationCode: "",
		businessLicensePhoto: "",
		usageTime: "",
		authorizeBeginTime: "",
		authorizeEndTIme: "",
		clientAuthorizationCodeNumber: null,
		contactsUserId: "",
		contactsUserName: "",
		contactsUserTel: "",
		contactsUserIdNo: "",
		contactsUserIdNoPhoto: "",
		contactsUserLoginName: "",
		platformId: "",
		states: true
	};
	drawerVisible.value = false;
};
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			//用户信息赋值
			userrequest.userName = fromVerification.value.contactsUserName;
			userrequest.userTel = fromVerification.value.contactsUserTel;
			userrequest.userIdNo = fromVerification.value.contactsUserIdNo;
			userrequest.userIdNoPhoto = fromVerification.value.contactsUserIdNoPhoto;
			userrequest.loginName = fromVerification.value.contactsUserLoginName;
			userrequest.platformId = globalStore.userInfo.platformInfo.id;
			userrequest.states = fromVerification.value.states;
			// //客户信息赋值
			fromVerification.value.platformId = globalStore.userInfo.platformInfo.id;
			// 编辑
			if (drawerProps.value.row.id) {
				await userInfoApi.UpdateUserInfo({ id: fromVerification.value.contactsUserId, ...userrequest });
				await companyInfoApi.UpdateCompanyInfo(fromVerification.value);
				ElMessage.success({ message: `${drawerProps.value.title}客户成功！` });
				drawerProps.value.getTableList!();
				drawerVisible.value = false;
				return;
			}
			//新增
			let { result } = await userInfoApi.AddUserInfo(userrequest);
			await userInfoApi.GetUserInfo({ id: result.data.id });
			fromVerification.value.contactsUserId = result.data.id;
			let res = await companyInfoApi.AddCompanyInfo(fromVerification.value);
			userInfoApi.UpdateUserInfo({ id: result.data.id, CompanyId: res.result.data.id });
			ElMessage.success({ message: `${drawerProps.value.title}客户成功！` });
			drawerProps.value.getTableList!();
			drawerVisible.value = false;
		} catch (error) {
			console.log(error);
		}
	});
};

defineExpose({
	acceptParams
});
</script>
